package org.openspml.providers.one_c.commands;

import org.openspml.message.DeleteRequest;
import org.openspml.message.SpmlResponse;
import org.openspml.providers.one_c.api.connection.GlobalContext;
import org.openspml.providers.one_c.api.users.InfoBaseUser;
import org.openspml.providers.one_c.api.users.InfoBaseUsersManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Removing user.
 * 
 * @author <A href="mailto:abashev at gmail dot com">Alexey Abashev</A>
 * @version $Id$
 */
public class DeleteRequestCommand {
	private final Logger log = LoggerFactory.getLogger(DeleteRequestCommand.class);

	public SpmlResponse execute(GlobalContext context, DeleteRequest request) {
		SpmlResponse response = request.createResponse();

		final String id = request.getIdentifierString();

		try {
			InfoBaseUsersManager manager = context.getInfoBaseUsers();
			InfoBaseUser user = manager.findByName(id);
			
			if (user == null) {
				log.warn("User with id [{}] not found", id);
				
				response.setResult(SpmlResponse.RESULT_FAILURE);
				response.setError(SpmlResponse.ERROR_NO_SUCH_IDENTIFIER);
				
				return response;
			} else {
				log.trace("Trying to delete user with id [{}]", id);

				user.delete();
				
				response.setResult(SpmlResponse.RESULT_SUCCESS);
			}
		} catch (Exception e) {
			log.error("Unable to create user [" + id + "]", e);
			
	        response.setError(SpmlResponse.ERROR_CUSTOM_ERROR);
	        response.setErrorMessage(e);
		}
		
		return response;
	}
}
